package com.sinping.qh.api.app.version.v1.user;

import com.sinping.qh.api.app.base.BaseAppEndPoint;
import com.sinping.qh.api.exception.HandlerException;
import com.sinping.qh.api.support.*;
import com.sinping.qh.domain.auth.User;
import com.sinping.qh.domain.user.ContentInfo;
import com.sinping.qh.domain.user.UserInfo;
import com.sinping.qh.dto.Insert;
import com.sinping.qh.dto.app.lab.LaboratoryByAppDTO;
import com.sinping.qh.dto.app.user.UserInfoNoContentDTO;
import com.sinping.qh.dto.app.user.UserLaboratoryDTO;
import com.sinping.qh.dto.mongo.auth.UserSessionDTO;
import com.sinping.qh.repository.mongo.user.ContentInfoRepository;
import com.sinping.qh.service.app.lab.impl.LaboratoryByAppServiceImpl;
import com.sinping.qh.service.app.user.IUserInfoService;
import com.sinping.qh.service.auth.IUserService;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.security.CryptoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @author zhangjin
 * @create 2018/6/9
 */
@Api(value = "app用户",description = "app用户API")
@RestController
@RequestMapping(value = Const.APP_URI_V1+"/user",name="用户")
public class UserAppEndPointV1 extends BaseAppEndPoint {

    @Autowired
    private IUserService userService;

    @Autowired
    LaboratoryByAppServiceImpl laboratoryByAppServiceByApp;

    @Autowired
    IUserInfoService iUserInfoService;

    @Autowired
    ContentInfoRepository contentInfoRepository;

    /**
     * 用户修改密码
     *
     * @param msg
     * @return ResDto
     */
    @ApiOperation(value = "修改密码", notes = "id，old_content,new_content参数不可为空，且位数与格式正确", consumes = MediaTypes.TEXT_HTML_UTF_8)
    @RequestMapping(value = "/setting/password", method = RequestMethod.PUT, name = "修改密码")
    public ResDto reset(@ApiParam(name = "msg", value = "{\"id\":\"1233\",\"old_password\":\"abc\",\"new_password\":\"\"}") @RequestParam String msg) {

        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        User user = JsonMapper.defaultMapper().fromJson(msg, User.class);
            checkNull(user,ConstEum.PARAM_ERROR);
            checkValidator(user, Insert.class,true);

            User oldUser = userService.selectById(user.getId());
            checkNull(oldUser,ConstEum.FAIL,"用户不存在");

            UserInfo one = userService.findMongoUserExist(user);
            checkNull(one,ConstEum.FAIL,"用户不存在");

        ContentInfo contentInfo=contentInfoRepository.findContentInfoByUserId(user.getId());
        String saleStr="";
        if(contentInfo!=null){
            saleStr=contentInfo.getSalt();
        }
        else{
            throw new HandlerException(ConstEum.FAIL,"账号异常,请联系管理员");
        }

        byte[] salt= Base64Utils.decodeFromString(saleStr);

            /*** 旧密码与数据库相同验证通过*/
            if (oldUser.getContent().equals(CryptoUtil.sha256(salt,user.getOldContent()))) {
                //修改密码时重新生成盐值
                byte[] newSalt=null;
                if(contentInfo!=null){
                    //如果有盐值重新生成盐值
                    newSalt= CryptoUtil.createSalt();
                }
                user.setContent(CryptoUtil.sha256(newSalt,user.getNewContent()));
                boolean update = userService.updateById(user);
                if (!update) {
                    throw new HandlerException(ConstEum.FAIL,"修改失败");
                }
                //更新mongoDB用户信息
                one.setContent(user.getContent());
                try {
                    userService.updateMongoUserInfo(one);
                } catch (Exception e) {
                    userService.updateById(oldUser);
                    throw new HandlerException(ConstEum.FAIL,"修改失败");
                }
                if(contentInfo!=null){
                    //修改成功保存盐值
                    contentInfo.setSalt(Base64Utils.encodeToString(newSalt));
                    contentInfo.setGmtModified(new Date());
                    contentInfoRepository.save(contentInfo);
                }
            } else {
                throw new HandlerException(ConstEum.FAIL,"旧密码错误");
            }
        resDto.setMsg(ConstEum.SUCCESS.getMessage());
        return resDto;
    }

    /**
     * 获取用户所负责的院系,无分页
     *
     * @return ResDto
     */
    @ApiOperation(value = "用户所负责的院系,无分页")
    @RequestMapping(value = "/mananger_unit", method = RequestMethod.GET, name = "用户所负责的院系,无分页")
    public ResDto getUserManagerUnit()
    {
        ResDto resDto = new ResDto(ConstEum.SUCCESS);

        UserSessionDTO userSessionDto=getUserSessionDto();

        List<UserLaboratoryDTO> userLaboratoryDTOList=
                laboratoryByAppServiceByApp.getUserLaboratory(userSessionDto);

        resDto.setMsg(ConstEum.SUCCESS.getMessage());
        resDto.setDatas(JsonMapper.defaultMapper().toJson(userLaboratoryDTOList));
        return resDto;
    }

    /**
     * 根据院系获取用户所负责的楼宇
     *
     * @return ResDto
     */
    @ApiOperation(value = "根据院系获取用户所负责的楼宇")
    @RequestMapping(value = "/buildingbyunit", method = RequestMethod.GET, name = "根据院系获取用户所负责的楼宇")
    public ResDto getUserBuildingByUnit(@ApiParam(name = "msg", value = "{\"unit_id\":\"8a4eb8b80cae412184fdfe3d53d7f18d\"}") @RequestParam String msg)
    {
        ResDto resDto = new ResDto(ConstEum.SUCCESS);

        Condition condition = JsonMapper.defaultMapper().fromJson(msg, Condition.class);
        checkNull(condition,ConstEum.PARAM_ERROR);

        UserSessionDTO userSessionDto=getUserSessionDto();

        List<LaboratoryByAppDTO> laboratoryByAppDTOList=
                laboratoryByAppServiceByApp.getUserBuildingByUnit(condition.getUnit_id(),userSessionDto);

        resDto.setMsg(ConstEum.SUCCESS.getMessage());
        resDto.setDatas(JsonMapper.defaultMapper().toJson(laboratoryByAppDTOList));
        return resDto;
    }

//    /**
//     * 获取所有院系
//     *
//     * @return ResDto
//     */
//    @ApiOperation(value = "获取所有院系")
//    @RequestMapping(value = "/units", method = RequestMethod.GET, name = "获取所有院系")
//    public ResDto getAllUnits()
//    {
//        ResDto resDto = new ResDto(ConstEum.SUCCESS);
//
//        List<UserInfoNoPasswordDTO> userInfoByAppDTOList=
//                iUserInfoService.getAllUnits();
//
//        resDto.setMsg(ConstEum.SUCCESS.getMessage());
//        resDto.setDatas(JsonMapper.defaultMapper().toJson(userInfoByAppDTOList));
//        return resDto;
//    }

    /**
     * 获取院系的检查人员
     *
     * @return ResDto
     */
    @ApiOperation(value = "获取院系的检查人员")
    @RequestMapping(value = "/checkuser", method = RequestMethod.GET, name = "获取院系的检查人员")
    public ResDto getAllCheckUsers(@ApiParam(name = "msg", value = "{\"name\":\"1233\"}") @RequestParam String msg)
    {
        ResDto resDto = new ResDto(ConstEum.SUCCESS);

        Condition condition =JsonMapper.defaultMapper().fromJson(msg,Condition.class);


        List<UserInfoNoContentDTO> userInfoByAppDTOList=
        iUserInfoService.getCheckUser(condition.getName());
        resDto.setMsg(ConstEum.SUCCESS.getMessage());
        resDto.setDatas(JsonMapper.defaultMapper().toJson(userInfoByAppDTOList));
        return resDto;
    }

    /**
     * 获取用户基本信息
     *
     * @return ResDto
     */
    @ApiOperation(value = "获取用户基本信息")
    @RequestMapping(value = "/userinfo", method = RequestMethod.GET, name = "获取用户基本信息")
    public ResDto getUserInfo()
    {
        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        String userSessionDto=
                iUserInfoService.findOne(getToken());
//
//
//        UserSessionDTO userSessionDTO=
//                BeanMapper.map(userSessionDto,UserSessionDTO.class);

        resDto.setMsg(ConstEum.SUCCESS.getMessage());
        resDto.setDatas(userSessionDto);
        return resDto;
    }
}
